import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//资源类
class ShareDate{
    private  int num=0;
    private Lock lock=new ReentrantLock();
    Condition condition= lock.newCondition();
    //防止虚假唤醒，多线程判断用while
    public  void incr()throws Exception{
        lock.lock();
        try{
            //1.判断
            while(num!=0){
                //等待，不能生产
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"\t"+num);
            //通知唤醒。
            condition.signalAll();
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                lock.unlock();
            }

    }

    public  void decr()throws Exception{
        lock.lock();
        try{
            //1.判断
            while(num==0){
                //等待，不能消费
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"\t"+num);
            //通知唤醒。
            condition.signalAll();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }

    }
}

public class ProdConsumer_TraditionalDemo {
    public static void main(String[] args) {
        ShareDate shareDate=new ShareDate();

        new Thread(()->{
            try {
                for (int i = 0; i <=5; i++) {
                    shareDate.incr();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        },"producer").start();

        new Thread(()->{
            try {
                for (int i = 0; i <=5; i++) {
                    shareDate.decr();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"consumer").start();

    }
}
